# 这是一种基于类的router定义方式 
require 'sinatra/base'

require 'sinatra/flash'
require_relative './lib/wordguesser_game.rb'

class WordGuesserApp < Sinatra::Base

    enable :sessions
    register Sinatra::Flash
  
    before do
        @game = session[:game] || WordGuesserGame.new('')
    end
  
    after do
        session[:game] = @game
    end
  
    # 下面是Sinatra语法的好示例，帮助你理解接下来的任务
    get '/' do
        redirect '/new'
    end
  
    get '/new' do
        # "hello world"
        erb :new
    end
  
    post '/create' do
        # 注释：获取参数中的word或者调用wordGuesserGame中的get_random_word方法获取一个随机的单词
        # 注意：不要修改下一行，autograder需要它
        word = params[:word] || WordGuesserGame.get_random_word

        # 注释：调用WordGuesserGame中的new方法，将前面的word传进去，得到@game，然后重定向到/show
        @game = WordGuesserGame.new(word)
        redirect '/show'
    end
  
    # 使用WordGuesserGame中存在的方法，来处理一个猜测请求
    # 如果这个猜测是重复的，设置刷新信息提示“你已经用过这个单词了”
    # 如果这个猜测是非法的，设置刷新信息提示“非法请求”
    # 然后跳转到show页面
    post '/guess' do
        letter = params[:guess].to_s[0]
        ### YOUR CODE HERE ###
        begin
            valid = @game.guess(letter)
        rescue ArgumentError
            flash[:message] = "Invalid guess."
        else
            unless valid
                flash[:message] = "You have already used that letter."
            end
        end
        redirect '/show'
    end
  
    get '/show' do
        ### YOUR CODE HERE ###
        erb :show # You may change/remove this line
    end
  
    get '/win' do
        ### YOUR CODE HERE ###
        erb :win # You may change/remove this line
    end
  
    get '/lose' do
        ### YOUR CODE HERE ###
        erb :lose # You may change/remove this line
    end
  
end
